<?php 

defined('IN_YYS')or exit('Access Denied.');
ini_set("display_errors","ON");
include dirname(__FILE__).'/control/wxpay.class.php';
class wxpay_url extends SystemAction {
	private $out_trade_no;
	public function __construct(){			
		$this->db=System::DOWN_sys_class('model');		
	} 	
	
	public function qiantai(){	
		if(_is_mobile()){
			$message = '_notemobile';
		}else{
			$message = '_note';
		}		
		$out_trade_no = $this->out_trade_no;
		$dingdaninfo = $this->db->YOne("select * from `@#_yonghu_addmoney_record` where `code` = '$out_trade_no'");
		if(!$dingdaninfo || $dingdaninfo['status'] == '未付款'){
			$message("支付成功，请进入用户中心!",LOCAL_PATH."/mobile/home/userbalance");			
		}else{
			if(empty($dingdaninfo['scookies'])){
				$message("充值成功!",LOCAL_PATH."/mobile/home/userbalance");
			}else{
				if($dingdaninfo['scookies'] == '1'){
					$isZhongChou = intval($dingdaninfo['is_zhongchou']);
					if($isZhongChou == 1){
						$message("支付成功!",LOCAL_PATH."/mobile/cart/paysuccesszc");
					}else{
						$message("支付成功!",LOCAL_PATH."/mobile/cart/paysuccess");
					}
				}else{
					$message("商品还未购买,请重新购买商品!",LOCAL_PATH."/member/cart/cartlist");
				}					
			}
		}
	}
	
	
	public function houtai()
	{
		$pay_type =$this->db->YOne("SELECT * from `@#_payment` where `pay_class` = 'wxpay' and `pay_start` = '1'");
		$pay_type_key = unserialize($pay_type['pay_key']);
		$key =  $pay_type_key['key']['val'];		//支付KEY
		$id =  $pay_type_key['id']['val'];		//支付商号ID
		
		//使用通用通知接口
		$notify = new Notify_pub();

		//存储微信的回调
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];	
		$notify->saveData($xml);
		//验证签名，并回应微信。
		//对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
		//微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
		//尽可能提高通知的成功率，但微信不保证通知最终能成功。
		if($notify->checkSign() == FALSE){
			$notify->setReturnParameter("return_code","FAIL");//返回状态码
			$notify->setReturnParameter("return_msg","签名失败");//返回信息
		}else{
			$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
		}
		$returnXml = $notify->returnXml();
		echo $returnXml;
		
		if($notify->checkSign() == TRUE)
		{
			if ($notify->data["return_code"] == "FAIL") {
				exit();
			}
			elseif($notify->data["result_code"] == "FAIL"){
				exit();
			}
			else{
				$this->out_trade_no=$notify->data["out_trade_no"];
			}	
				
			$ret = $this->weixin_chuli();					
			$this->qiantai();
		}else{
			exit();
		}
	}
	private function weixin_chuli()
	{
		$pay_type =$this->db->YOne("SELECT * from `@#_payment` where `pay_class` = 'wxpay' and `pay_start` = '1'");
		$out_trade_no = $this->out_trade_no;
		$dingdaninfo = $this->db->YOne("select * from `@#_yonghu_addmoney_record` where `code` = '$out_trade_no'");
		
		$notify = new Notify_pub();

		//存储微信的回调
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];	
		$notify->saveData($xml);
		$yzmoney=$notify->data["total_fee"]/100;
		if(!$dingdaninfo){ return false;}	//没有该订单,失败
		$c_money = intval($dingdaninfo['money']);
		if($c_money!=$yzmoney){
			//return false;
		}
		if($dingdaninfo['status'] == '已付款'){
			return '已付款';
		}
		$configss = System::DOWN_App_config("user_fufen",'','member');//福分/经验/佣金
		$baifenbi = $configss['fufen_yuansong']; //每一元返回的佣金
		$c_money = $c_money*$baifenbi;
		$uid = $dingdaninfo['uid'];
		$time = time();
		
		$this->db->tijiao_start();
		$up_q1 = $this->db->Query("UPDATE `@#_yonghu_addmoney_record` SET `pay_type` = '微信wap支付', `status` = '已付款' where `id` = '$dingdaninfo[id]' and `code` = '$dingdaninfo[code]'");
		$up_q2 = $this->db->Query("UPDATE `@#_yonghu` SET `money` = `money` + $c_money where (`uid` = '$uid')");			
		$up_q3 = $this->db->Query("INSERT INTO `@#_yonghu_zhanghao` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '账户', '充值', '$c_money', '$time')");
		
		if($up_q1 && $up_q2 && $up_q3){			
			$this->db->tijiao_commit();
		}else{
			$this->db->tijiao_rollback();
			return '充值失败';
		}			
		if(empty($dingdaninfo['scookies'])){					
			return "充值完成";	//充值完成	
		}
		//到这里微信的钱已经充值到用户账户中
		//开始走正常途径支付
		$type = $dingdaninfo['orderType'];
		$this->type = $type;
		$scookies = unserialize($dingdaninfo['scookies']);			
		$pay = System::DOWN_App_class('pay','pay');
		$pay->scookie = $scookies;
		/* 手动设置coupon_ids和addressId */
		$yonghu = $this->db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
		$pay->coupon_ids = $yonghu['coupon_ids'];
		$pay->addressId = $yonghu['addressId'];
		$pay->goods_ids = $yonghu['goods_ids'];
		$pay->cartZgList = $yonghu['cartZgList'];
		$pay->coupon_0 = unserialize($yonghu['coupon_0']);
		$pay->coupon_1 = unserialize($yonghu['coupon_1']);
		$pay->uid = $uid;
		$cartZgList = unserialize($pay->cartZgList);
		if(current($cartZgList)[0]['isZhongChou'] == 1){
			$pay->isZhongChou = 1;
		}
		/* 设置完毕 */
		$ok = $pay->init($uid,$pay_type['pay_id'],'go_record');	//乐购商品	

		if($ok != 'ok'){
			$_COOKIE['Cartlist'] = '';_setcookie('Cartlist',NULL);			
			return '商品购买失败';	//商品购买失败			
		}

		$check = $pay->start_pay(1);
		if($check){
			//成功
			if($pay->isZhongChou == 1){
				//标记订单已完成
				$res = updateSet(array('status'=>4),'order_list',$pay->dingdancode,'order_sn');
				if(!$this->yaojiang($pay->dingdancode) || !$res){
					_setcookie('cartList',NULL);
					return '商品购买失败';
				}
				return "商品购买成功";
			}else{
				$this->orderId = $pay->orderId;
				$dingdancode = $pay->dingdancode;
				$this->db->Query("UPDATE `@#_yonghu_addmoney_record` SET `scookies` = '1',`orderCode` = '$dingdancode' where `code` = '$out_trade_no' and `status` = '已付款'");
				$_COOKIE['Cartlist'] = '';_setcookie('Cartlist',NULL);
			}
			return "商品购买成功";
		}else{
			return '商品购买失败';
		}			

	}

	

	public function yaojiang($order_sn){
		$order = $this->db->YOne("select * from `@#_order_list` where `order_sn` = '$order_sn' and `is_randcoupon` = '0'");
		if(!$order){
			return false;
		}else{
			return $this->makeRandCoupon($order_sn);
		}
	}

	public function makeRandCoupon($order_sn){
		/*查询有几单*/
		$order_item = $this->db->YList("select * from `@#_order_item` where `order_sn` = '$order_sn'");
		$total_num = 0;
		foreach($order_item as $key => $one){
			$total_num += $one['supplierPercent'];
		}
		$pay = System::DOWN_App_class('pay','pay');
		$pay->makeRandCoupon($order_sn,$total_num);
		$this->db->query("update `@#_order_list` set `is_randcoupon` = '1',`is_ok` = '1' where `order_sn` = '$order_sn'");
		return true;
	}
	
}//

?>